import { HttpError, toSuccess, useEntityManager } from "@sker/core";
import { AutoUser, KsDevice } from "@sker/entities";
import { useData } from "@sker/runtime";
import { z } from "zod";


export default async () => {
    const input = z.object({
        token: z.string(),
        deviceid: z.any()
    });
    const body = input.parse(useData())

    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) throw new HttpError(`请重新登录`)
        if (user.device_count < user.max_count) {
            const device = await m.findOne(KsDevice, { where: { id: parseInt(body.deviceid) } })
            if (!device) {
                throw new HttpError(`请输入正确的设备编号`)
            }
            if (device.owner) {
                throw new HttpError(`此设备已绑定，请先解绑后更换`)
            }
            await m.update(KsDevice, device.id, { owner: user.mobile })
            await m.update(AutoUser, user.id, { device_count: user.device_count + 1 })
            return toSuccess(true)
        }
        throw new HttpError(`已达最大数量，请解绑后操作`)
    })
}
